/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import { filterObj } from '../utils/util';
import { deleteAction, getAction, downFile, uploadFile } from '../api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN } from "../store/mutation-types"

export default  {
  data(){
    return {
      // 正在导出标志
      exporting:false,
      exportPercent:0,
      exportStatus:'导出',
      //token header
      tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource:[],
      /* 分页参数 */
      ipagination:{
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30','50','100','300','1000'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter:{
        column: 'createDateTime',
        order: 'desc',
      },
      /* table加载状态 */
      loading:false,
      importLoading:false,// 导入loading
      importPercent:0,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus:false,
      backQueryParam:{}
    }
  },
  mounted() {
    this.initDictConfig();
    this.loadData();
    this.backQueryParam = JSON.parse(JSON.stringify(this.queryParam));
  },
  methods:{
    beforeLoadData(){
      return true;
    },
    loadData(arg) {
      if(!this.beforeLoadData()){
        return;
      }
      if(!this.url.list){
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if(this.ipagination !== false){
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        let params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          this.afterLoadData(res);
          if (res.success) {
            this.dataSource = res.result.content;
            this.ipagination.total = res.result.totalElements;
          }
        }).finally(()=>{
          this.loading = false;
        })
      }else{
        let params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          this.afterLoadData(res);
          if (res.success) {
            this.dataSource = res.result;
          }
        }).finally(()=>{
          this.loading = false;
        })
      }

    },
    afterLoadData(res){

    },
    initDictConfig(){
    },

    getQueryParams() {
      //获取查询条件
      let sqp = {};
      let specQuery = [];
      for (let queryParamKey in this.queryParam) {
        specQuery.push(this.queryParam[queryParamKey]);
      }
      var param = Object.assign(sqp,{"specJson":encodeURI(JSON.stringify(specQuery))}, this.isorter );
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return filterObj(param);
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    searchQuery() {
      this.loadData(1);
    },
    searchReset() {
      this.queryParam=JSON.parse(JSON.stringify(this.backQueryParam));
      this.loadData(1);
    },
    batchDel: function () {
      if(!this.url.deleteBatch){
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {

        let ids = this.selectedRowKeys.join(",")
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              }
            })
          }
        });
      }
    },
    handleMenuClick: function(e){
      this[e.key]();
    },
    handleDelete: function (id) {
      if(!this.url.delete){
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      this.$confirm({
        title: "确认删除",
        content: "是否删除选中数据?",
        onOk: function () {
          deleteAction(that.url.delete, {id:id}).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.loadData();
            }
          })
        }
      });
    },
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleAdd: function () {
      this.$refs.modalForm.add();
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.ipagination = pagination;
      this.loadData();
    },
    handleToggleSearch(){
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.loadData();
    },
    handleDetail:function(record){
      this.$refs.modalForm.title="详情";
      this.$refs.modalForm.disableSubmit = true;
      this.$refs.modalForm.edit(record);
    },

    doExport(url, param){
      if(typeof(url) != 'string'){
        url = null;
      }
      let u = url;
      if(!u){
        u = this.url.export;
      }
      if(!u){
        this.$message.error("请设置url.export属性!")
        return
      }
      this.exporting=true;
      this.exportPercent=0;
      downFile(u,param, (event)=>{
        if(event.total){
          this.exportPercent = event.loaded/event.total*100;
        }
      }).then(res=>{
        this.exporting=false;
        this.exportPercent=0;
        let contentDisposition = res.headers['content-disposition'];
        if(!contentDisposition){
          this.$message.warn("未获取到文件下载回应头content-disposition");
          return;
        }
        let index = contentDisposition.indexOf('filename=');
        if(index<0){
          this.$message.warn("未获取到文件下载回应头content-disposition中filename=");
          return;
        }
        let filename = contentDisposition.substr(index+9);
        let a = document.createElement('a');
        a.href = URL.createObjectURL(res.data);
        a.download = decodeURIComponent(filename);
        a.click();
      })
    },
    handleExportSelected(url){
      let rowKeys = this.selectedRowKeys;
      if(!rowKeys || rowKeys.length == 0){
        this.$message.warn("请先选择行");
        return;
      }
      let sqp = {};
      let specQuery = [{type:'in', column: 'id', value:rowKeys.join(",")}];
      let param = Object.assign(sqp,{"specJson":encodeURI(JSON.stringify(specQuery))}, this.isorter );
      param = filterObj(param);
      this.doExport(url, param);
    },
    handleExport(url){
      this.doExport(url, this.getQueryParams());
    },

    handleExportMustQueryParams(url){
      let existQueryParams = false;
      for (let queryParamKey in this.queryParam) {
        if(this.queryParam[queryParamKey]['value']){
          existQueryParams = true;
          break;
        }
      }
      if(!existQueryParams){
        this.$message.warn("请选择查询条件");
        return;
      }
      this.handleExport(url);
    },

    handleExportById(url,id){
      let sqp = {};
      let specQuery = [{type:'eq', column: 'id', value:id}];
      let param = Object.assign(sqp,{"specJson":encodeURI(JSON.stringify(specQuery))}, this.isorter );
      param = filterObj(param);
      this.doExport(url, param);
    },


    /**
     * 导出大数据信息，可能超时
     * @param exportCmdUrl 导出命令url
     * @param exportInfoUrl 查询导出信息url
     * @param exportDoUrl 执行导出url
     */
    handleExportBigData(exportCmdUrl, exportInfoUrl, exportDoUrl){
      exportCmdUrl = exportCmdUrl||this.url.exportCmd;
      exportInfoUrl = exportInfoUrl||this.url.exportInfo;
      exportDoUrl = exportDoUrl||this.url.exportDo;
      if(!exportCmdUrl ){
        this.$message.error("请设置url.exportCmd属性!")
        return
      }
      if(!exportInfoUrl ){
        this.$message.error("请设置url.exportInfo属性!")
        return
      }
      if(!exportDoUrl){
        this.$message.error("请设置url.exportDo属性!")
        return
      }
      this.exporting=true;
      this.exportPercent=0;
      let that = this;
      let id = '';
      let exportStatusBack = that.exportStatus;
      async function getExportInfo(){
        let info = that.exportStatus;
        if(info) {
          let infoRes = await getAction(exportInfoUrl, { exportId: id });
          if (infoRes.success) {
            info = infoRes.result;
          }
          if(info){
            that.exportStatus = info;
            setTimeout(getExportInfo, 500);
          }else{
            that.exporting=true;
            that.exportPercent=0;
            downFile(exportDoUrl,{ exportId: id }, (event)=>{
              if(event.total){
                that.exportPercent = event.loaded*100/event.total;
              }
            }).then(res=>{
              that.exporting=false;
              that.exportPercent=0;
              let contentDisposition = res.headers['content-disposition'];
              if(!contentDisposition){
                that.$message.warn("未获取到文件下载回应头content-disposition");
                return;
              }
              let index = contentDisposition.indexOf('filename=');
              if(index<0){
                that.$message.warn("未获取到文件下载回应头content-disposition中filename=");
                return;
              }
              let filename = contentDisposition.substr(index+9);
              let a = document.createElement('a');
              a.href = URL.createObjectURL(res.data);
              a.download = decodeURIComponent(filename);
              a.click();
            }).finally(()=>{
              that.exportStatus=exportStatusBack;
            })
          }
        }
      }
      getAction(exportCmdUrl, this.getQueryParams())
        .then(res=>{
          if(res.success){
            id = res.result;
            this.exporting=false;
            getExportInfo();
          }
        })


    },
    // 导入
    customImportRequest(request){
      console.log(request);

      let url = request.action;
      if(!url){
        url = this.url.import;
      }
      if(!url){
        this.$message.error("请设置url.import属性!")
        return
      }
      let file = request.file;
      let formData = new FormData();
      let filename = request.filename;
      if(!filename){
        filename = 'file';
      }
      formData.append(filename, file);
      if (request.data) {
        for (let key in request.data) {
            formData.append(key,request.data[key])
        }
      }
      this.importLoading = true;
      uploadFile(url, formData, (event)=>{
        if(event.total){
          this.importPercent = event.loaded/event.total*100;
        }
      }).then(res=>{
        if(res.success){
          this.$message.success('文件上传成功');
          this.loadData();
        }
      })
        .finally(()=>{
          this.importLoading = false;
        });
    },



  }

}
